<template>
	<view>
		<view class="formList">
			<u--form labelPosition="left" labelWidth="80px" :model="model" :rules="rules" ref="form">
				<u-form-item :label="$t('public.cutNo')+$t('public.colon')" prop="production.cutNo" borderBottom>
					<u-input v-model="model.production.cutNo" type="input"
						:placeholder="$t('public.pleaseSelect')+$t('public.cutNo')" disabled>
						<template slot="suffix">
							<i class="iconfont icon-saoyisao" @click="scanHandle"></i>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item :label="$t('public.productionNo')+$t('public.colon')" prop="production.no" borderBottom>
					<u-input v-model="model.production.no" type="input"
						:placeholder="$t('public.pleaseSelect')+$t('public.productionNo')" disabled>
						<template slot="suffix">
							<u-icon name="arrow-down" @click="searchAllNo"></u-icon>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item :label="$t('public.part')+$t('public.colon')" prop="production.part" borderBottom>
					<u-input v-model="model.production.part" type="input"
						:placeholder="$t('public.pleaseSelect')+$t('public.part')" disabled>
						<template slot="suffix">
							<u-icon name="arrow-down" @click="searchAllPart"></u-icon>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item :label="$t('homepage.WorkReport.reporter')+$t('public.colon')" prop="production.name"
					borderBottom>
					<u-input v-model="model.production.name" type="input"
						:placeholder="$t('public.pleaseSelect')+$t('homepage.WorkReport.reporter')" disabled>
						<template slot="suffix">
							<u-icon name="arrow-down" @click="searchAllName"></u-icon>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item :label="$t('page.Procedure')+$t('public.colon')" prop="production.procedure">
					<u-textarea v-model="model.production.procedure" :placeholder="$t('page.Procedure')" disabled></u-textarea>
				</u-form-item>
			</u--form>
			<u-picker :show="noSelect" :columns="noList" @cancel="noCancel" @confirm="noConfirm">
			</u-picker>
			<u-picker :show="partSelect" :columns="partList" @cancel="partCancel" @confirm="partConfirm">
			</u-picker>
			<u-picker :show="nameSelect" :columns="nameList" @cancel="nameCancel" @confirm="nameConfirm">
			</u-picker>
		</view>
		<!-- 底部按钮 -->
		<bottomBtn fixed :leftText="$t('public.reset')" :rightText="$t('public.submit')" @rightBtn="submitBtn"
			@leftBtn="resetBtn">
		</bottomBtn>
		
		<u-popup :show="show" :mode="popupData.mode" :round="popupData.round" :closeable="popupData.closeable"
			@close="close">
			<view class="u-popup-slot" style="height: 42vh;">
				<u--text :text="$t('homepage.WorkReport.completedQuantity')"
					customStyle="font-size:16px;font-weight:800;margin:15px auto;"></u--text>
				<view style="margin:25px 60px;display: flex;">
					<u-icon name="bookmark-fill" color="red" size="30"></u-icon>
					<u--text :text="$t('homepage.WorkReport.num')+$t('public.colon')"
						customStyle="font-size:18px;"></u--text>
					<zy-number-box :value="num" @change="valChange" color="#fff" bgcolor="#409efe" discolor="#fff"
						disbgcolor="#9AC9F9" size="16" integer>
					</zy-number-box>
				</view>
				<u-button type="primary" :text="$t('public.sure')" :disabled="disabled"
					customStyle="bottom:5px;margin:0 5px;position:fixed;border-radius:50px;width:97%;" @click="sure">
				</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getProductionCode,
		getProductionNos,
		getProductionTaskByNo,
		procedureQueryListByField,
		getUsersByCurrent,
		queryUncompletedReportNew,
		handSaveTaskReport,
	} from "@/api/homepage.js"
	export default {
		data() {
			var checkProce = (rule,value,callback) => {
			  if (value == "暂无数据") {
				callback(this.$t('homepage.WorkReport.procNull'))
			  } else {
				callback()
			  }
			}
						
			return {
				model: {
					production: {
						cutNo: '',
						no: '',
						part: '',
						name: this.$store.state.loginData.realname,
						procedure: "",
					},
				},
				rules: {
					'production.no': [{
						required: true,
						message: this.$t('homepage.WorkReport.noUnNull'),
						trigger: ['change', 'blur'],
					}],
					'production.cutNo': [{
						required: true,
						message: this.$t('homepage.WorkReport.cutNoUnNull'),
						trigger: ['change', 'blur'],
					}],
					'production.name': [{
						required: true,
						message: "汇报人不能为空",
						trigger: ['change', 'blur'],
					}],
					'production.procedure': [{
						required: true,
						validator: checkProce,
						trigger: ['change', 'blur'],
					}],
				},
				noList: [],
				noSelect: false,
				productionTaskId: '',
				cutNoId: '',
				partList: [],
				partSelect: false,
				nameList: [],
				nameSelect: false,
				nameLists: [],
				procedureId: "", //工序id
				reportUserId: this.$store.state.loginData.id,
				show: false,
				num: 0,
				disabled: true,
				popupData: {
					round: 10,
					mode: 'bottom',
					closeable: true,
				},
				dataList: [],
				billUserName: ""
			}
		},
		onPullDownRefresh() {
			setTimeout(function() {
				uni.redirectTo({
					url: "/pages/HomePage/WorkReportNostrict/index"
				})
				uni.stopPullDownRefresh();
			}, 1000);
		},
		computed: {
			procedure() {
				let data = {
					id: "",
					name: "暂无数据"
				}
				let arr = uni.getStorageSync("procedureData")
				if (arr !== "") {
					arr.forEach((item, index) => {
						if (item.switch) {
							data = {
								id: item.procedureId,
								name: item.procedureName
							}
						}
					})
				}
				return data
			}
		},
		watch: {
			procedure: {
				handler(n, o) {
					this.model.production.procedure = n.name
					this.procedureId = n.id
				},
				immediate: true,
				deep: true
			}
		},
		onLoad() {
			var _this = this
			uni.$on('scancodedate', function(data) {
				_this.searchList(data.code)
			})
			
			this.billUserName = this.$store.state.loginData.realname
		},
		onUnload() {
			// 移除监听事件      
			uni.$off('scancodedate')
		},
		methods: {
			// 左侧扫一扫图标事件
			scanHandle() {
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module")
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_result) {
							let obj = ret.resp_result.replace(/\s/g, "")
							this.searchList(obj);
						} else {
							uni.showToast({
								title: this.$t('topSearch.scanTip'),
								icon: "none",
								duration: 3000
							})
						}
					})
			},
			// 裁剪单号查询
			searchList(e) {
				this.model.production.cutNo = e
				getProductionCode({
					cuttingSheetNo: e,
				}).then((res) => {
					if (res.code == 0) {
						this.model.production.part = res.data.partName
						this.model.production.no = res.data.productionNo
						this.productionTaskId = res.data.productionTaskId //单号id
						this.cutNoId = res.data.cuttingSheetId //裁剪单号id
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
				});
			},
			// 生产单号
			noCancel() {
				this.noSelect = false
			},
			noConfirm(e) {
				this.noSelect = false
				var no = e.value
				this.model.production.no = no.toString()
				this.productionTaskId = no.toString()
			},
			searchAllNo() {
				this.noSelect = true
				getProductionNos({}).then((res) => {
					var noLists = []
					noLists.push(res.data)
					this.noList = noLists
				})
			},
			// 部件
			partCancel() {
				this.partSelect = false
			},
			partConfirm(e) {
				this.partSelect = false
				var part = e.value
				this.model.production.part = part.toString()
			},
			searchAllPart() {
				this.$refs.form.validate().then(res => {
					this.partList = []
					this.partSelect = true
					procedureQueryListByField({
						fieldName: 'cuttingSheetId',
						fieldValue: this.cutNoId
					}).then((res) => {
						var str = [];
						for (var i = 0; i < res.data.length; i++) {
							if (str.indexOf(res.data[i].partName) == -1) {
								str.push(res.data[i].partName)
							}
						}
						let obj = []
						obj = str
						this.partList.push(obj)
					})
				})
			},
			// 汇报人
			nameCancel() {
				this.nameSelect = false
			},
			nameConfirm(e) {
				this.nameSelect = false
				var name = e.value
				this.nameLists.forEach((item) => {
					if (item.realname == name) {
						this.reportUserId = item.id
					}
				})
				this.model.production.name = name.toString()
				this.billUserName = name.toString()
			},
			searchAllName() {
				// this.$refs.form.validate().then(res => {
				this.nameList = []
				this.nameLists = []
				this.nameSelect = true
				getUsersByCurrent().then((res) => {
					this.nameLists = res.data
					var str = [];
					for (var i = 0; i < res.data.length; i++) {
						str.push(res.data[i].realname)
					}
					let obj = []
					obj = str
					this.nameList.push(obj)
				})
				// })
			},
			//弹出层关闭
			close() {
				this.show = false
				this.num = 0
				this.disabled = true
			},
			//弹出层中数量
			valChange(e) {
				let tableNum = 0, newArr = []
				
				for (let i = 0; i < this.dataList.length; i++) {
					let newArrSec = []
					for (let j = 0; j < this.dataList[i].length; j++) {
						newArrSec.push(this.dataList[i][j])
					}
					
					let addVal = 0
					for (let m = 0; m < newArrSec.length; m++) {
						addVal += newArrSec[m].perBindNum
					}
					
					newArr.push(addVal)
				}
				
				let minValue = newArr[0]
				 
				for (let i = 1; i < newArr.length; i++) {
				  if (newArr[i] < minValue) {
				    minValue = newArr[i]
				  }
				}
				
				if (e > minValue) {
					uni.$u.toast("不可超过剩余数量，请重新输入")
					this.disabled = true
				} else {
					this.disabled = false
					this.num = e
				}
			},
			getTableList(id) {
				console.log(id)
				queryUncompletedReportNew({
					cuttingSheetNo: this.cutNoId, //裁剪单号
					productionTaskId: this.productionTaskId, //生产单号id
					partName: this.model.production.part, //部件名称
					produceList: id, //工序
				}).then((res) => {
					if (res.code == 0) {
						console.log(res.data)
						this.show = true
						this.dataList.push(res.data)
					} else {
						console.log(res)
						uni.$u.toast(res.message)
					}
				})
			},
			submitBtn() {
				uni.removeStorage({
					key: 'workReportList',
				})
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form.validate().then(res => {
					console.log(this.procedureId)
					this.dataList = []
					
					let proArr = this.procedureId.split(",")
					
					for(let i = 0; i < proArr.length; i++) {
						this.getTableList(proArr[i])
					}
					
				}).catch(errors => {
					// uni.$u.toast(errors.message)
				})
			},
			resetBtn() {
				const validateList = ['production.no', 'production.cutNo',
					'production.part', 'production.name'
				]
				this.$refs.form.resetFields()
				this.$refs.form.clearValidate()
				setTimeout(() => {
					this.$refs.form.clearValidate(validateList)
					// 或者使用 this.$refs.form1.clearValidate()
				}, 10)
			},
			getSubData(params) {
				let numListData = [], forLength = 1
				
				if (params.length == 1) {
					for (var i = 0; i < forLength; i++) {
						let numList = {
							equipmentId: this.id,
							cardId: params[i].cardId,
							procedureName: params[i].procedureName,
							procedureId: params[i].procedureId,
							procedureCode: params[i].procedureNo,
							num: this.num,
							cuttingSheetId: this.cuttingSheetId,
							productionTaskId: this.productionTaskId,
							reportUserId: this.reportUserId,
							billUserName: this.billUserName,
							procedureIdList: params[i].procedureId
						}
						
						numListData.push(numList)
					}
				} else {
					
					let addNum = 0, addIndex = 0, addTotal = 0, lastNum = 0
					for (let i = 0; i < params.length; i++) {
						addNum += params[i].perBindNum
						addIndex++
						if (this.num - addNum <= 0) {
							break
						}
					}
					
					for (let i = 0; i < addIndex - 1; i++) {
						addTotal += params[i].perBindNum
					}
					
					forLength = addIndex
					lastNum = this.num - addTotal
					
					if (lastNum == 0) {
						for (var i = 0; i < forLength; i++) {
							let numList = {
								equipmentId: this.id,
								cardId: params[i].cardId,
								procedureName: params[i].procedureName,
								procedureId: params[i].procedureId,
								procedureCode: params[i].procedureNo,
								num: params[i].perBindNum,
								cuttingSheetId: this.cuttingSheetId,
								productionTaskId: this.productionTaskId,
								reportUserId: this.reportUserId,
								billUserName: this.billUserName,
								procedureIdList: this.params[i].procedureId
							}
							
							numListData.push(numList)
						}
					} else {
						for (var i = 0; i < forLength; i++) {
							let numList
							if (i < forLength - 1) {
								numList = {
									equipmentId: this.id,
									cardId: params[i].cardId,
									procedureName: params[i].procedureName,
									procedureId: params[i].procedureId,
									procedureCode: params[i].procedureNo,
									num: params[i].perBindNum,
									cuttingSheetId: this.cuttingSheetId,
									productionTaskId: this.productionTaskId,
									reportUserId: this.reportUserId,
									billUserName: this.billUserName,
									procedureIdList: params[i].procedureId
								}
							} else {
								numList = {
									equipmentId: this.id,
									cardId: params[i].cardId,
									procedureName: params[i].procedureName,
									procedureId: params[i].procedureId,
									procedureCode: params[i].procedureNo,
									num: lastNum,
									cuttingSheetId: this.cuttingSheetId,
									productionTaskId: this.productionTaskId,
									reportUserId: this.reportUserId,
									billUserName: this.billUserName,
									procedureIdList: params[i].procedureId
								}
							}
							
							numListData.push(numList)
						}
					}
				}
				
				return numListData
			},
			//弹出层中确认
			sure() {

				let proLength = this.procedureId.split(",").length, newArr = [],
				newArrSec = []
				
				for(let i = 0; i < proLength; i++) {
					let newArrThird = this.getSubData(this.dataList[i])
					for(let j = 0; j < newArrThird.length; j++) {
						newArrSec.push(newArrThird[j])
					}
				}
				
				console.log(newArrSec)
				
				handSaveTaskReport({
					taskReportArray: JSON.stringify(newArrSec)
				}).then((res) => {
					if (res.code == 0) {
						this.close()
						this.resetBtn()
						uni.$u.toast(res.message)
					} else {
						uni.$u.toast(res.message)
					}
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	.formList {
		background-color: #fff;
		margin: 10px;
		padding: 10px 10px 20px 10px;
		width: calc(100%-40px);
		height: 100%;
		border-radius: 4px;
	}
</style>